package com.lagou.java;

import com.sun.net.httpserver.Authenticator;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import sun.font.TrueTypeFont;

import javax.xml.soap.Node;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ZkClientTest {

    private static String basePath = "/netty_provider";

    public static void main(String[] args) throws Exception{
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        System.out.println("zookeeper session established ... ");

        zkClient.createPersistent(basePath, true);
        System.out.println("success create znode");

        zkClient.deleteRecursive(basePath);
        System.out.println("sucess delete znode.");

//        List<String> children = zkClient.getChildren(basePath);
//        System.out.println(children);

        // 注册监听事件
        Set<String> cacheNodes = new HashSet<>();
//        zkClient.subscribeChildChanges(basePath, new IZkChildListener() {
//            public void handleChildChange(String parentPath,
//                                          List<String> currentChilds) throws Exception {
//                currentChilds.forEach(node -> {
//                    if (!cacheNodes.contains(node)) {
//                        System.out.println(node + " > 新创建");
//                    }
//                });
//                cacheNodes.forEach(node ->{
//                    if (!currentChilds.contains(node)) {
//                        System.out.println(node + " > 被删除");
//                    }
//                });
//
//                cacheNodes.addAll(currentChilds);
//                System.out.println(parentPath + " 's child changed currentChilds:" + currentChilds);
//            }
//        });
        zkClient.createPersistent(basePath);
        Thread.sleep(1000);
        zkClient.createPersistent(basePath + "/c1");
        Thread.sleep(1000);
        zkClient.delete(basePath + "/c1");
        Thread.sleep(1000);
    }
}
